import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:exams_app/gen_a/A.dart';
import 'package:exams_app/net/Address.dart';
import 'package:exams_app/net/DioManager.dart';
import 'package:exams_app/net/persisten_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';

class MyProfileLogic extends GetxController{


  int page = 0;

 Rx<CollectionModel> collectionModel;

 EasyRefreshController esController = EasyRefreshController();

  var dataList = List();


  /// 空数据

  emptyData(){
    if(dataList.length == 0){
      return Container(
        // width: double.infinity,
        // height: double.infinity,
        child: Center(
          child: SizedBox(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(

                    child: Column(
                      children: [
                        Image.asset(A.assets_nodata_icon,width: 100,height: 100,),
                        Text('暂无数据',style: TextStyle(fontSize: 13,fontWeight: FontWeight.w600),),
                      ],
                    )
                ),
              ],
            ),
          ),
        ),
      );
    }else{
      return null;
    }
  }

  /// 下拉刷新

  Future<void> onRefresh()async{
     page = 0;
     requestDataWithCollection(true,page: page);
   }
  ///  上拉加载更多
   Future<void> onLoad()async{
     page++;
     requestDataWithCollection(false,page: page);
     await Future.delayed(Duration(milliseconds: 250), () {

     });
   }

  /// 我的资料
  void requestDataWithCollection(bool isHeader,{int page = 0})async{


    var  params = {
      'page':page,
      'limit':'10',
      'folder_id': '0',
      'domain': "[('favorited_ids', '=', ${await PersistentStorage().getStorage('uid')})]",
    };

    String result = await DioUtils(url: await PersistentStorage().getStorage('urlStr')).
    postModel(Address.getattt,function_name:'_api_page',model:'documents.document',params:params );
    Map json = jsonDecode(result);

    collectionModel = CollectionModel.fromJson(json).obs;


    if(page == 0){

      esController.resetLoadState();
      dataList.clear();
      dataList.addAll(collectionModel.value.data);
    }else{

      if(json['data'].length>0){
        // for(int i = 0;i<model.data.length;i++){
        //   model.data[i].isSelect = false;
        // }

        dataList.addAll(collectionModel.value.data);
      }else if(json['data'].length <= 0||json['data']==null){
        // _esController.finishLoad(success: true,noMore: true);
        esController.finishLoad(success: true, noMore: true);
        BotToast.showText(text: '暂无更多');
      }
    }

    update();

  }

 /// 取消关注

 void requestDataWithCancelCollection(var favorited_ids,var documentID) async {
   String result = await DioUtils(
       url: await PersistentStorage().getStorage('urlStr'))
       .postModel(
       '/api/v1/write/${documentID}',
       model: 'documents.document',
       params: {'form-field-many2many3-favorited_ids': favorited_ids,'examapp':'True'});
   Map json = jsonDecode(result);
 }

 /// 关注
 void requestDataWithFouce(var favorited_ids,var documentID) async {
   String result = await DioUtils(
       url: await PersistentStorage().getStorage('urlStr'))
       .postModel(
       '/api/v1/write/${documentID}',
       model: 'documents.document',
       params: {'form-field-many2many4-favorited_ids': favorited_ids,'examapp':'True'});
   Map json = jsonDecode(result);
   // BotToast.showText(text: json['message']);
   BotToast.showText(text: '收藏成功!');
 }


 @override
  void onInit() {
    requestDataWithCollection(true,page: 0);
    // TODO: implement onInit
    super.onInit();
  }

}

class CollectionModel {
  int folderId;
  String search;
  List<CollectionModelData> data;
  int searchCount;
  int errcode;
  String errmsg;
  String message;

  CollectionModel(
      {this.folderId,
        this.search,
        this.data,
        this.searchCount,
        this.errcode,
        this.errmsg,
        this.message});

  CollectionModel.fromJson(Map<String, dynamic> json) {
    folderId = json['folder_id'];
    search = json['search'];
    if (json['data'] != null) {
      data = new List<CollectionModelData>();
      json['data'].forEach((v) {
        data.add(new CollectionModelData.fromJson(v));
      });
    }
    searchCount = json['search_count'];
    errcode = json['errcode'];
    errmsg = json['errmsg'];
    message = json['message'];
  }
}

class CollectionModelData {
  int id;
  String icon;
  String createDate;
  String writeDate;
  String pastTime;
  String name;
  String url;
  var mimetype;
  int folderId;
  String folderIdName;
  String type;
  String previewUrl;
  var download_url;

  CollectionModelData(
      {this.id,
        this.icon,
        this.download_url,
        this.createDate,
        this.writeDate,
        this.pastTime,
        this.name,
        this.url,
        this.mimetype,
        this.folderId,
        this.folderIdName,
        this.type,
        this.previewUrl});

  CollectionModelData.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    icon = json['icon'];
    createDate = json['create_date'];
    writeDate = json['write_date'];
    pastTime = json['past_time'];
    name = json['name'];
    url = json['url'];
    mimetype = json['mimetype'];
    folderId = json['folder_id'];
    folderIdName = json['folder_id_name'];
    type = json['type'];
    previewUrl = json['preview_url'];
    download_url = json['download_url'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['icon'] = this.icon;
    data['create_date'] = this.createDate;
    data['write_date'] = this.writeDate;
    data['past_time'] = this.pastTime;
    data['name'] = this.name;
    data['url'] = this.url;
    data['mimetype'] = this.mimetype;
    data['folder_id'] = this.folderId;
    data['folder_id_name'] = this.folderIdName;
    data['type'] = this.type;
    data['preview_url'] = this.previewUrl;
    return data;
  }
}

